/**
 * bitstore.h
 *
 *  Created on: 17/09/2012
 *      Author: peter
 */

#ifndef BITSTORE_H_
#define BITSTORE_H_


#include <iostream>
#include <fstream>
#include <cassert>
#include <cstring>
#include <stdint.h>

using std::cerr;
using std::endl;
using std::fstream;
using std::string;
using std::ios;

class BitStore
{
public:
	BitStore();
	~BitStore();
	void open(const string name, ios::openmode m);
	void close();
	void out(uint64_t buf, short len);
	void out(uint8_t *buf, short len);
	uint64_t in(short len);
private:
	void putbit(bool bit);
	bool getbit();
	fstream datafile;
	char outbuf;
	char inbuf;
	short outpos;
	short inpos;
	ios::openmode filemod;
};

// dette er ikke tjekket, måske er byte order forkert.
template <typename T>
void store(BitStore &st, T &data)
{
	st.out((uint8_t*)&(data), sizeof(T));
}

template <typename T>
void retrieve(BitStore &st, T &data)
{
	uint8_t *buf = (uint8_t*) &data;
	size_t i;
	for (i=0; i<sizeof(T); i++) {
		buf[i] = st.in(8);
	}
}

#endif /* BITSTORE_H_ */
